import { env } from '@/shared/constants';
import { ArticleDto, ArticleSource, ListArticleFormatDto } from '@/shared/interfaces/generated';
import { RootState } from '@/shared/store';
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';

export const articleApi = createApi({
  reducerPath: 'articleApi',
  tagTypes: ['Article'],
  baseQuery: fetchBaseQuery({
    baseUrl: env.apiUrl,
    prepareHeaders: async (headers, query) => {
      const authResult = (query.getState() as RootState).auth;
      if (authResult && authResult.accessToken) {
        headers.set('authorization', `Bearer ${authResult.accessToken}`);
      }
      headers.set('Request-Source', 'site');
      return headers;
    },
    credentials: 'include',
  }),
  endpoints: (builder) => ({
    addArticleToFavourites: builder.mutation<void, { id?: string; articleId: string }>({
      query: ({ id, articleId }) => ({
        url: `/users/${id}/favoriteArticles:add`,
        body: { articleId: +articleId },
        method: 'POST',
      }),
      invalidatesTags: ['Article'],
    }),
    deleteArticleFromFavourites: builder.mutation<void, { id?: string; articleId: string }>({
      query: ({ id, articleId }) => ({
        url: `/users/${id}/favoriteArticles:remove`,
        body: { articleId: +articleId },
        method: 'POST',
      }),
      invalidatesTags: ['Article'],
    }),

    getArticles: builder.query<
      { articles: ArticleDto[] },
      {
        limit?: number;
        offset?: number;
        search?: string;
        'orderBy[publishedAt]'?: 'DESC' | 'ASC';
        'filters[topics]'?: string;
        'filters[formats]'?: string;
        'filters[publicationStatusId]'?: number;
        /** @example "2023-02-02" */
        'filters[maxPublishedAt]'?: string;
        /** @example "2023-02-02" */
        'filters[minPublishedAt]'?: string;
      }
    >({
      query: (params) => ({
        url: '/v2/articles/',
        params,
      }),
      providesTags: ['Article'],
    }),
    getFavoriteArticles: builder.query<
      { articles: ArticleDto[] },
      {
        id: string | number;
        limit?: number;
        offset?: number;
        search?: string;
        'orderBy[publishedAt]'?: 'DESC' | 'ASC';
        'filters[topics]'?: string;
        'filters[formats]'?: string;
        'filters[publicationStatusId]'?: number;
        /** @example "2023-02-02" */
        'filters[maxPublishedAt]'?: string;
        /** @example "2023-02-02" */
        'filters[minPublishedAt]'?: string;
      }
    >({
      query: ({ id, ...params }) => ({
        url: `/users/${id}/favoriteArticles/`,
        params: { ...params },
      }),
      providesTags: ['Article'],
    }),
    getArticleFormats: builder.query<ListArticleFormatDto, void>({
      query: () => ({
        url: '/articleFormats',
      }),
      providesTags: ['Article'],
    }),

    getSingleArticle: builder.query<ArticleDto, string | number>({
      query: (id) => ({
        url: `/v2/articles/${id}`,
      }),
      providesTags: ['Article'],
    }),
    getArticleSources: builder.query<{ sources: ArticleSource[] }, string | number>({
      query: (id) => ({
        url: `/v2/articles/${id}/sources`,
      }),
      providesTags: ['Article'],
    }),

    setArticleViewed: builder.mutation<void, string>({
      query: (id) => ({
        url: `/v2/articles/${id}:setViewed`,
        method: 'POST',
      }),
    }),
  }),
});
